//
//  LDAudioResumePlayer.swift
//  DingDongZP
//
//  Created by LeMac on 16/12/31.
//  Copyright © 2016年 51ledian.com. All rights reserved.
//

import UIKit
import AVFoundation

class LDAudioResumePlayer: NSObject {
    
    //播放
    var isPlaying = false
    var isPrepared = false
    var timer:NSTimer?
    var item:AVPlayerItem?
    
    static let instance = LDAudioResumePlayer()
    
    //
    private var palyProgress:((player:LDAudioResumePlayer,progress:Float)->())?
    private var palyfinish:((player:LDAudioResumePlayer) -> ())?
    
    //播放器
    lazy var player:AVPlayer={
        
        let play = AVPlayer.init()
        return play
    }()
    
    class func sharePlayer() -> LDAudioResumePlayer {
        
        return instance
    }
    
    override init() {
        
        super.init()
        initKVO()
    }
    //准备url
    func prepareAudioURL(url:String?){
        
        if player.currentItem != nil {
            player.currentItem?.removeObserver(self, forKeyPath: "status")
        }
        //创建一个item资源
        item = AVPlayerItem(URL: NSURL(string: url ?? "defalut")!)
        
        item!.addObserver(self, forKeyPath: "status", options: .New, context: nil)
        item!.addObserver(self, forKeyPath: "loadedTimeRanges", options: .New, context: nil)
        
    
//        self.player.replaceCurrentItemWithPlayerItem(item)
    }
    
    /*****************播放 暂停*****************/
    func play() {
        
        if item == nil {
            return
        }
        self.player.replaceCurrentItemWithPlayerItem(item!)
        if (!isPrepared) {
            return
        }
        
        player.play()
        isPlaying = true
        if timer == nil {
            
            timer = NSTimer.bk_timerWithTimeInterval(0.5, block: { [weak self] (times) in
                
                if self?.palyProgress != nil {
                    
//                    let progress = (self?.player.currentTime().value.toIntMax())! / (self?.player.currentTime().timescale.toIntMax())!;
                    guard let currT = self?.player.currentTime().value else { return }
                    guard let timeS = self?.player.currentTime().timescale else { return }
                    
                    let progress = Float(currT) / Float(timeS)
                    self?.palyProgress!(player:self!,progress:progress)
                }
                
            }, repeats: true)
        }
        
    }
    
    func pause() {
        
        if !isPlaying {
            return
        }
        player.pause()
        isPlaying = false
        timer?.invalidate()
        timer = nil;
    }
    //寻找时间点
    func seekToTime(time:Float64) {
        pause()
        player.seekToTime(CMTimeMakeWithSeconds(time, player.currentTime().timescale)) { [weak self] (isfinish) in
            
            if isfinish  { self?.play() }
        }
    }
    //更新进度条
    func updatePlayStatus(closure: (player:LDAudioResumePlayer,progress:Float)->()) {
        palyProgress = closure
    }
    //播放结束
    func palyFinished(closure:(player:LDAudioResumePlayer) -> ()) {
        
        self.palyfinish = closure
    }
    
    //监听
    
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        guard let playerItem = object as? AVPlayerItem else { return }
        
        if keyPath == "loadedTimeRanges"{
            // 缓冲进度
        }else if keyPath == "status"{
            // 监听状态改变
            if playerItem.status == AVPlayerItemStatus.ReadyToPlay{
                // 只有在这个状态下才能播放
//                self.play()
                debugPrint("---加载正常")
            }else{
                debugPrint("---加载异常")
            }
        }
    }
    
    func initKVO() {
    
        //播放结束时间
        NSNotificationCenter.defaultCenter().rac_addObserverForName(AVPlayerItemDidPlayToEndTimeNotification, object: nil).subscribeNext {
            [weak self] (obj) in
            if obj == nil { return }
            
            if self?.palyfinish == nil {
                return
            }
            
            self?.palyfinish!(player: self!)
        }
    }
    //
    func ifPlaying() ->Bool {
        
        return isPlaying
    }
    
    class var sharedInstance:LDAudioResumePlayer {
        struct Staics {
            static let instance = LDAudioResumePlayer()
        }
        return Staics.instance
    }
}
